/*
{*******************************************************************}
{                                                                   }
{       KS-GANTT DotNet Library                                     }
{       Gantt-Charting Control for Windows Forms                    }
{                                                                   }
{       Copyright (c) 2009 - 2012 by Kroll-Software                 }
{       All Rights Reserved                                         }
{                                                                   }
{   This code is provided 'as is',                                  }
{   without warranties of any kind. Use at your own risk.           }                                                              
{                                                                   }
{   As a license holder of the KS-Gantt Control,                    }
{   you may freely redistribute executables based on                }
{   and created with these contents.                                }
{   You can modify the source code to meet your needs.              }
{                                                                   }
{   However, you must not publish, redistribute or transfer         }
{   this source code to 3rd parties under any conditions.           }
{                                                                   } 
{*******************************************************************}
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KS.Common;

namespace MiGuava.SqlServer
{
    public partial class CreateNewDatabaseDialog : Form
    {
        private GanttSqlDB SqlDB = null;
        private bool bRunning = false;

        private bool m_Created = false;
        public bool DatabaseCreated
        {
            get
            {
                return m_Created;
            }
        }

        protected string m_SqlScriptPath = "";
        public string SqlScriptPath
        {
            get
            {
                return m_SqlScriptPath;
            }
            set
            {
                m_SqlScriptPath = value;
            }
        }

        public string UserName
        {
            get
            {
                return ucSqlServerConnect1.UserName;
            }
            set
            {
                ucSqlServerConnect1.UserName = value;
            }
        }


        public string Password
        {
            get
            {
                return ucSqlServerConnect1.Password;
            }
            set
            {
                ucSqlServerConnect1.Password = value;
            }
        }

        public string Server
        {
            get
            {
                return ucSqlServerConnect1.Server;
            }
            set
            {
                ucSqlServerConnect1.Server = value;
            }
        }

        public string Database
        {
            get
            {
                return ucSqlServerConnect1.Database;
            }
            set
            {
                ucSqlServerConnect1.Database = value;
            }
        }

        public SQLAuthTypes SQLAuth
        {
            get
            {
                return ucSqlServerConnect1.SQLAuth;
            }
            set
            {
                ucSqlServerConnect1.SQLAuth = value;
            }
        }

        public string ConnectionString
        {
            get
            {
                return ucSqlServerConnect1.ConnectionString;
            }
        }

        public CreateNewDatabaseDialog()
        {
            InitializeComponent();
            
            ucSqlServerConnect1.ConnectionMode = ucSqlServerConnect.ConnectionModes.CreateDatabase;
            this.FormClosing += new FormClosingEventHandler(CreateNewDatabaseDialog_FormClosing);
        }

        void CreateNewDatabaseDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bRunning)
                e.Cancel = true;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            ucSqlServerConnect1.InitLoad();
            LoadSQL();
        }

        private void ShowStatus(string S)
        {
            txtStatus.Text += S + "\r\n";
            txtStatus.SelectionStart = txtStatus.Text.Length;
            txtStatus.ScrollToCaret();
            //txtStatus.Update();
            Application.DoEvents();
        }

        void SqlDB_ScriptStatus(object sender, SqlDBTextEventArgs e)
        {
            ShowStatus(e.Text);            
        }

        private void CreateNewDatabaseDialog_Load(object sender, EventArgs e)
        {
            lblInfo.Text = Properties.Resources.SQLCreateDatabaseInfo;
        }

        private void LoadSQL()
        {
            if (!Strings.FileExists(m_SqlScriptPath))
            {
                Program.ErrMsgBox("SQL-Script file not found:\r\n" + m_SqlScriptPath);
                return;
            }
            
            System.IO.StreamReader SqlFile = null;

            try
            {
                SqlFile = new System.IO.StreamReader(m_SqlScriptPath);
                txtSql.Text = SqlFile.ReadToEnd();
                SqlFile.Close();
            }
            catch (Exception ex)
            {
                Program.ErrMsgBox(ex.Message);
            }
            finally
            {
                if (SqlFile != null)
                {
                    SqlFile.Dispose();
                    SqlFile = null;
                }
            }            
        }


        void DBConn_InfoMessage(object sender, System.Data.SqlClient.SqlInfoMessageEventArgs e)
        {
            ShowStatus(e.Message + "\r\n");            
        }

        private void ExecuteSQL(string SQL)
        {
            ShowStatus(SQL + "\r\n");
            SqlDB.ExecuteUpdateSQL(SQL);
        }

        private void cmdCreate_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabOptions;
            if (!ucSqlServerConnect1.IsValid(true, true))
            {                
                return;
            }

            switch (Program.QuestionMsgBox(String.Format(Properties.Resources.SQLCreateDatabaseQuestion, ucSqlServerConnect1.Database)))
            {
                case DialogResult.No:
                    this.DialogResult = DialogResult.No;
                    this.Close();
                    return;

                case DialogResult.Cancel:
                    return;
            }            

            cmdCreate.Enabled = false;
            cmdCancel.Enabled = false;            

            SqlDB = new GanttSqlDB();
            SqlDB.ScriptStatus += new GanttSqlDB.ScriptStatusEventHandler(SqlDB_ScriptStatus);            

            SqlDB.DBServer = ucSqlServerConnect1.Server;
            SqlDB.DBCatalog = "master";
            SqlDB.DBWinSecurity = (ucSqlServerConnect1.SQLAuth == SQLAuthTypes.SQLAuth_Win);
            if (SqlDB.DBWinSecurity)
            {
                SqlDB.DBPassword = "";
                SqlDB.DBUser = "";
            }
            else
            {
                SqlDB.DBPassword = ucSqlServerConnect1.Password;
                SqlDB.DBUser = ucSqlServerConnect1.UserName;
            }

            txtStatus.Clear();
            tabControl1.SelectedTab = tabStatus;            
            
            string strDataBaseName = "[" + ucSqlServerConnect1.Database + "]";
            m_Created = false;

            try
            {
                bRunning = true;
                SqlDB.BaseConnect();

                if (!SqlDB.CheckServerVersion())
                {
                    string strException = "";

                    try
                    {
                        strException = String.Format(Properties.Resources.SQLInvalidVersionError, SqlDB.DBConn.ServerVersion);
                    }
                    catch (Exception)
                    {
                        strException = String.Format(Properties.Resources.SQLInvalidVersionError, "unknown");
                    }

                    throw new Exception(strException);
                }
                
                SqlDB.DBConn.InfoMessage += new System.Data.SqlClient.SqlInfoMessageEventHandler(DBConn_InfoMessage);

                // Create the Database
                ExecuteSQL("CREATE DATABASE " + strDataBaseName);
                ExecuteSQL("USE " + strDataBaseName);

                SqlDB.RunSqlScript(m_SqlScriptPath);

                SqlDB.Disconnect();
                SqlDB.DBCatalog = ucSqlServerConnect1.Database;
                SqlDB.SaveSettings();
                m_Created = true;   
            }
            catch (Exception ex)
            {
                ShowStatus(ex.Message + "\r\n");
                Program.ErrMsgBox(ex.Message);                
            }
            finally
            {                
                SqlDB.Dispose();
                bRunning = false;
            }

            if (m_Created)
            {
                Program.InfoMsgBox(String.Format(Properties.Resources.SQLDatabaseCreated, ucSqlServerConnect1.Database));
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                cmdCreate.Enabled = true;
                cmdCancel.Enabled = true;
            }
        }        
    }
}